// pages/order/list.js
//index.js  
//获取应用实例  
var app = getApp();
var common = require("../../utils/common.js");
Page({
  data: {
    winWidth: 0,
    winHeight: 0,
    // tab切换  
    currentTab: 0,
    isStatus: 'pay',//10待付款，20待发货，30待收货 40、50已完成
    page: 0,
    refundpage: 0,
    //orderList0:[],
    orderList1: [],
    orderList2: [],
    orderList3: [],
    orderList4: [],
    orderList5: [],
    goodsurl: app.d.hostUrl + app.d.goodsurl,
  },
  onLoad: function (options) {
    this.initSystemInfo();
    this.setData({
      currentTab: parseInt(options.currentTab),
      isStatus: options.otype
    });
    if (options.otype == 'pay'){
      var site_name = '待付款';
    } else if (options.otype == 'ship') {
      var site_name = '待发货';
    } else if (options.otype == 'sign') {
      var site_name = '待收货';
    } else if (options.otype == 'review') {
      var site_name = '已完成';
    }else{
      var site_name = '';
    }
    wx.setNavigationBarTitle({
      title: site_name
    });

    if (this.data.currentTab == 5) {
      this.loadReturnOrderList();
    } else {
      this.loadOrderList();
    }
  },
  getOrderStatus: function () {
    return this.data.currentTab == 0 ? 1 : this.data.currentTab == 2 ? 2 : this.data.currentTab == 3 ? 3 : 0;
  },

  //取消订单
  removeOrder: function (e) {
    var that = this;
    var orderId = e.currentTarget.dataset.orderId;
    wx.showModal({
      title: '提示',
      content: '你确定要取消订单吗？',
      success: function (res) {
        res.confirm && wx.request({
          url: app.d.hostUrl + 'wapi/orders_cancel.html',
          method: 'post',
          data: {
            order_id: orderId,
            seesionid: app.globalData.userInfo.sessionId,
            openid: app.globalData.userInfo.openid,
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            //--init data
            var status = res.data.ret;
            if (status == 0) {
              wx.showToast({
                title: '操作成功！',
                duration: 2000
              });
              that.loadOrderList();
            } else {
              wx.showToast({
                title: res.data.msg,
                duration: 2000
              });
            }
          },
          fail: function () {
            // fail
            wx.showToast({
              title: '网络异常！',
              duration: 2000
            });
          }
        });

      }
    });
  },

  //确认收货
  recOrder: function (e) {
    var that = this;
    var orderId = e.currentTarget.dataset.orderId;
    wx.showModal({
      title: '提示',
      content: '你确定已收到宝贝吗？',
      success: function (res) {
        res.confirm && wx.request({
          url: app.d.hostUrl + '/Api/Order/orders_edit',
          method: 'post',
          data: {
            id: orderId,
            type: 'receive',
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            //--init data
            var status = res.data.status;
            if (status == 1) {
              wx.showToast({
                title: '操作成功！',
                duration: 2000
              });
              that.loadOrderList();
            } else {
              wx.showToast({
                title: res.data.msg,
                duration: 2000
              });
            }
          },
          fail: function () {
            // fail
            wx.showToast({
              title: '网络异常！',
              duration: 2000
            });
          }
        });

      }
    });
  },

  loadOrderList: function () {
    var that = this;
    wx.request({
      url: app.d.hostUrl + 'wapi/order_list.html',
      method: 'post',
      data: {
        seesionid: app.globalData.userInfo.sessionId,
        openid: app.globalData.userInfo.openid,
        order_type: that.data.isStatus,
        page: that.data.page,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var status = res.data.ret;
        if (status == 0) {
          var list = res.data.data;
        } else {
          var list = [];
        } console.log(list);
        that.setData({
          orderList: list,
        });
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },
  //点击加载更多
  getMore: function (e) {
    var that = this;
    var page = that.data.page;
    that.setData({
      page: page + 1,
    });
    this.loadOrderList();
  },
  onReachBottom: function () {
    var that = this;
    var page = that.data.page;
    that.setData({
      page: page + 1,
      isStatus: e.target.dataset.otype,
    });
    this.loadOrderList();
  }, 
  loadReturnOrderList: function () {
    var that = this;
    wx.request({
      url: app.d.hostUrl + 'wapi/order_refund.html',
      method: 'post',
      data: {
        seesionid: app.globalData.userInfo.sessionId,
        openid: app.globalData.userInfo.openid,
        page: that.data.refundpage,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data.data;
        var status = res.data.ret;
        if (status == 0) {
          that.setData({
            orderList5: that.data.orderList5.concat(data),
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            duration: 2000
          });
        }
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },

  // returnProduct:function(){
  // },
  initSystemInfo: function () {
    var that = this;

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  bindChange: function (e) {
    var that = this;
    that.setData({ currentTab: e.detail.current });
  },
  switchNav: function (e) {
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      var current = e.target.dataset.current;
      that.setData({
        currentTab: parseInt(current),
        isStatus: e.target.dataset.otype,
      });

      //没有数据就进行加载
      switch (that.data.currentTab) {
        case 0:
          !that.data.orderList0.length && that.loadOrderList();
          break;
        case 1:
          !that.data.orderList1.length && that.loadOrderList();
          break;
        case 2:
          !that.data.orderList2.length && that.loadOrderList();
          break;
        case 3:
          !that.data.orderList3.length && that.loadOrderList();
          break;
        case 4:
          !that.data.orderList4.length && that.loadOrderList();
          break;
        case 5:
          that.data.orderList5.length = 0;
          that.loadReturnOrderList();
          break;
      }
    };
  },
  /**
   * 微信支付订单
   */
  // payOrderByWechat: function(event){
  //   var orderId = event.currentTarget.dataset.orderId;
  //   this.prePayWechatOrder(orderId);
  //   var successCallback = function(response){
  //     console.log(response);
  //   }
  //   common.doWechatPay("prepayId", successCallback);
  // },

  payOrderByWechat: function (e) {
    var order_id = e.currentTarget.dataset.orderid;
    //var order_sn = e.currentTarget.dataset.ordersn;
    if (!order_id) {
      wx.showToast({
        title: "订单异常!",
        duration: 2000,
      });
      return false;
    }
    wx.request({
      url: app.d.hostUrl + 'wapi/wxpay.html',
      data: {
        order_id: order_id,
        //order_sn: order_sn,
        seesionid: app.globalData.userInfo.sessionId,
        openid: app.globalData.userInfo.openid,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }, // 设置请求的 header
      success: function (res) {
        if (res.data.status == 0) {
          var order = res.data.data;
          wx.requestPayment({
            timeStamp: order.timeStamp,
            nonceStr: order.nonceStr,
            package: order.package,
            signType: 'MD5',
            paySign: order.paySign,
            success: function (res) {
              wx.showToast({
                title: "支付成功!",
                duration: 2000,
              });
              setTimeout(function () {
                wx.navigateTo({
                  url: '../user/dingdan?currentTab=2&otype=deliver',
                });
              }, 3000);
            },
            fail: function (res) {
              wx.showToast({
                title: res,
                duration: 3000
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            duration: 2000
          });
        }
      },
      fail: function (e) {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    })
  },
  onShareAppMessage: function () {
    return {
      title: '极好生活商城',
      path: '/pages/index/index?scene=invite%3D' + app.globalData.user_id,
      success: function (res) {
        wx.showToast({
          title: '分享成功',
          duration: 2000
        });
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },
  /**
   * 调用服务器微信统一下单接口创建一笔微信预订单
   */
  //   prePayWechatOrder: function(orderId){
  //     var uri = "/ztb/userZBT/GetWxOrder";
  //     var method = "post";
  //     var dataMap = {
  //       SessionId: app.globalData.userInfo.sessionId,
  //       OrderNo: orderId
  //     }
  //     console.log(dataMap);
  //     var successCallback = function (response) {
  //       console.log(response);
  //     };
  //     common.sentHttpRequestToServer(uri, dataMap, method, successCallback);
  //   }
})